<template>
  <div class="app-container">
    <div class="search-container">
      <el-form :model="searchParam" :inline="true">
        <el-form-item label="工厂" label-width="40px !important">
          <el-select
            placeholder="请选择工厂"
            v-model="searchParam.plantId"
            clearable
          >
            <el-option
              v-for="item in options"
              :key="item.id"
              :value="item.id"
              :label="item.organizationCode"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="年份" label-width="40px !important">
          <el-select
            placeholder="请选择年份"
            v-model="searchParam.workCalendarYear"
            clearable
          >
            <el-option
              v-for="item in yearOptions"
              :key="item"
              :value="item"
              :label="item"
            />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="search"
            ><i-ep-search />搜索</el-button
          >
          <el-button @click="reset"><i-ep-refresh />重置</el-button>
        </el-form-item>
      </el-form>
    </div>

    <el-card shadow="never" class="table-container">
      <template #header>
        <el-button type="success" plain @click="setCalendarType"
          ><i-ep-setting />设置日历类型</el-button
        >
        <el-button type="primary" plain @click="enterFreeSettingPage"
          ><i-ep-setting />维护节假日</el-button
        >
      </template>

      <!-- 年度日历展示（有搜索数据） -->
      <div v-if="showCalendar" class="yearDateCalener">
        <MdmDateCalender
          :year="detail?.workCalendarYear ?? searchParam?.workCalendarYear"
          :detail="detail"
          :freeDates="freeDates"
          :planDates="planDates"
          v-for="(item, index) in 12"
          :month="index"
          :key="index"
        />
      </div>

      <!-- 年度日历展示（无搜索数据） -->
      <div v-else class="w-[100%]">
        <el-empty
          :image-size="200"
          :image="noData2"
          description="请选择工厂和年份，并点击搜索"
        />
      </div>
    </el-card>

    <!-- 日历设置弹窗 -->
    <el-dialog
      :close-on-click-modal="false"
      v-model="dialogVisible"
      title="设置日历类型"
      width="500"
      align-center
      draggable
      :destroy-on-close="true"
    >
      <el-form
        ref="menuFormRef"
        :model="formData"
        :rules="rules"
        label-width="100px"
      >
        <el-form-item label="工厂">
          <span>{{ typeObject?.plantCode || "" }}</span>
        </el-form-item>
        <el-form-item label="年份">
          <span>{{ typeObject?.workCalendarYear || "" }}</span>
        </el-form-item>
        <el-form-item label="日历类型" prop="typeId">
          <el-select v-model="formData.typeId" clearable>
            <el-option
              v-for="item in typeList"
              :key="item.id"
              :label="item.workCalendarTypeName"
              :value="item.id"
            />
          </el-select>
          <el-button
            v-if="!typeList.length"
            @click="enterTypeSettingPage"
            type="primary"
            text
            class="ml-[5px]"
            small
          >
            立即设置
          </el-button>
        </el-form-item>
      </el-form>

      <template #footer>
        <div class="dialog-footer">
          <el-button @click="dialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="setType" :loading="postLoading">
            确 认
          </el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import noData2 from "@/assets/images/noData2.png";
import request from "@/utils/request";
import { ref, reactive, onMounted } from "vue";
import { ElMessage } from "element-plus";
import router from "@/router";
import dayjs from "dayjs";
import {
  workingDays,
  getDatesBetween,
} from "@/components/MdmDateCalender/index";
import { useDictStoreHook } from "@/store/modules/dictionary"; // 引入
const dictionaryStore = useDictStoreHook();

defineOptions({
  name: "MDMMDMWORKCALENDARDETAIL",
  inheritAttrs: false,
});

// 获取工厂列表
const options = ref();
async function getPlants() {
  const { data } = await request({
    url: "/system/sysOrganization/getList",
    method: "post",
    data: { organizationType: 3 },
  });
  options.value = data;
  console.log(options.value[0].id);
  searchParam.plantId = options.value[0].id;
}

// 获取年度列表
const yearOptions = ref();
async function getYears() {
  const { data } = await request({
    url: "/system/dateInfo/getYearList",
    method: "post",
    data: {},
  });
  yearOptions.value = data;
}

// 初始化搜索项
let searchParam = reactive({
  plantId: "",
  workCalendarYear: "",
});

// 获取日历详情
const detail: any = ref({});
const showCalendar = ref(false);
const freeDates = ref([]);
const planDates = ref([]);
async function search() {
  if (!searchParam.plantId || !searchParam.workCalendarYear) {
    ElMessage.warning("请先选择工厂和年份");
    return;
  }
  // detail.value = {};
  freeDates.value = [];
  planDates.value = [];
  const { data } = await request({
    url: "/mdm/mdmworkcalendar/getWithDetails",
    method: "post",
    data: {
      ...searchParam,
    },
  });
  detail.value = data;
  getFreeDates(data);
  getPlanDates(data?.freeDayList);
  showCalendar.value = true;
}

// 获取休假日期 例如：[6,7]
function getFreeDates(data: any) {
  if (data && data?.plantId) {
    Object.keys(workingDays).forEach((key) => {
      if (data[key] === 0 || data[key] === null) {
        freeDates.value = [...freeDates.value, workingDays[key]];
      }
    });
  }
}

// 获取计划休假、上班日期
function getPlanDates(data: any) {
  const planArr: any[] = [];
  data?.map((item: any) => {
    const b_date = dayjs(item.beginDate).format("YYYY-MM-DD");
    const e_date = dayjs(item.endDate).format("YYYY-MM-DD");
    const arr_date = getDatesBetween(b_date, e_date);
    const freeDayName = dictionaryStore.filterDictName(
      "FreeDayType",
      item.freeDayType
    );
    arr_date.map((e) => {
      const obj = {
        time: e,
        pollution: freeDayName.indexOf("假") !== -1 ? "休" : "班",
        freeDayType: item.freeDayType,
        freeDayName: freeDayName,
        id: item.id,
        workCalendarId: item.id,
      };
      planArr.push(obj);
    });
  });
  planDates.value = planArr;
}

// 重置筛选条件
function reset() {
  Object.assign(searchParam, {
    plantId: "",
    workCalendarYear: "",
  });
  detail.value = {};
  showCalendar.value = false;
}

// 初始化日历类型数据&校验规则
const formData = reactive({
  typeId: "",
});
const rules = reactive({
  typeId: [{ required: true, message: "请选择日历类型", trigger: "change" }],
});
const menuFormRef = ref(ElForm);

// 获取日历类型
const typeList = ref();
const dialogVisible = ref(false);
const typeObject = ref();
function isPassReport() {
  if (!detail.value) {
    if (searchParam.plantId && searchParam.workCalendarYear) {
      const obj = options.value.find((e) => e.id === searchParam.plantId);
      typeObject.value = {
        plantId: searchParam.plantId,
        workCalendarYear: searchParam.workCalendarYear,
        plantCode: obj.organizationCode,
      };
    } else {
      typeObject.value = null;
      ElMessage.warning("请先选择工厂和年份，并点击搜索");
    }
  } else {
    if (detail.value?.plantId && detail.value?.workCalendarYear) {
      const obj = options.value.find((e) => e.id === detail.value?.plantId);
      typeObject.value = {
        plantId: detail.value?.plantId,
        workCalendarYear: detail.value?.workCalendarYear,
        plantCode: obj.organizationCode,
      };
    } else {
      typeObject.value = null;
      ElMessage.warning("请先选择工厂和年份，并点击搜索");
    }
  }
}

// 打开日历类型设置弹窗
async function setCalendarType() {
  isPassReport();
  if (typeObject.value) {
    getTypeList(typeObject.value.plantId).then(() => {
      dialogVisible.value = true;
      getCurrentType();
      setTimeout(() => {
        menuFormRef.value.clearValidate();
      }, 100);
    });
  }
}

// 获取日历类型列表
async function getTypeList(plantId) {
  const { data } = await request({
    url: "/mdm/mdmworkcalendartype/gettypes",
    method: "get",
    params: {
      plantId: plantId,
    },
  });
  typeList.value = data && data?.length ? data : [];
}

//设置日历类型
const postLoading = ref(false);
function setType() {
  menuFormRef.value.validate(async (isValid: boolean) => {
    if (isValid) {
      postLoading.value = true;
      const data = await request({
        url: "/mdm/mdmworkcalendar/updatetype",
        method: "post",
        data: {
          workCalendarYear: typeObject.value?.workCalendarYear,
          plantId: typeObject.value?.plantId,
          typeId: formData.typeId,
        },
      }).finally(() => {
        postLoading.value = false;
      });
      ElMessage.success("设置成功");
      search();
      dialogVisible.value = false;
    }
  });
}

// 日历类型id
const workCalendarId = ref("");
//根据工厂和年度获取当前日历类型
async function getCurrentType() {
  const { data } = await request({
    url: "/mdm/mdmworkcalendar/getthistype",
    method: "post",
    data: {
      workCalendarYear: typeObject.value?.workCalendarYear,
      plantId: typeObject.value?.plantId,
    },
  });
  workCalendarId.value = data?.id ? data?.id : "";
  formData.typeId = data?.workCalendarTypeId ? data?.workCalendarTypeId : "";
}

// 跳转日历类型设置页面
function enterTypeSettingPage() {
  dialogVisible.value = false;
  router.push({
    name: "MDMMDMWORKCALENDARTYPE",
  });
}

// 跳转休息设置页面
function enterFreeSettingPage() {
  isPassReport();
  if (!typeObject.value?.plantId || !typeObject.value?.workCalendarYear) {
    return;
  } else {
    getCurrentType().then(() => {
      if (!workCalendarId.value) {
        ElMessage.warning("请先设置日历类型");
      } else {
        router.push({
          name: "MDMMDMFREEDAY",
          query: {
            plantCode: typeObject.value.plantCode,
            plantId: typeObject.value.plantId,
            workCalendarYear: typeObject.value.workCalendarYear,
            id: workCalendarId.value,
          },
        });
      }
    });
  }
}

onMounted(() => {
  getPlants();
  getYears();
});
</script>

<style lang="scss" scoped>
/* 小于 768px  */
@media only screen and (max-width: 768px) {
  :deep(.cc-calendar) {
    flex: 0 0 calc(100% / 2 - 10px) !important;
  }
}

/* 768px - 1400px  */
@media screen and (min-width: 768px) and (max-width: 1400px) {
  :deep(.cc-calendar) {
    flex: 0 0 calc(100% / 4 - 10px) !important;
  }
}

/* 大于 1400px  */
@media screen and (min-width: 1400px) {
  :deep(.cc-calendar) {
    flex: 0 0 calc(100% / 6 - 10px) !important;
  }
}
:deep(.table-container .el-card__body) {
  padding: 6px 15px 20px 7px;
  min-height: calc(100vh - 250px);
}
.yearDateCalener {
  display: flex;
  flex-wrap: wrap;
  min-height: 400px;
  // justify-content: center;
  :deep(.cc-calendar) {
    padding: 10px;
    margin-left: 10px;
    margin-top: 10px;
    box-sizing: border-box;
  }
}
</style>
